#coding:utf-8
from flask import request
from flask import session
from flask  import render_template
import json
import threading
import libs.util.redis_queue as redis_queue
import libs.weixinApi.get_openid_oauth2 as get_openid_oauth2
import models.biding as biding_info
import models.stuinfo as stu_info


def scan_qr(app):
    @app.route('/note/login/waiting')
    def waiting_response():
        temp_code = request.args.get('state')

        # session['stu_id'] = 121270026
        # session['name'] = '愚吉'
        # return '0'
        '需要增加一个线程来定时释放（其实就是pub啦，然后标注为超时)'

        sub = redis_queue.sub(temp_code)
        '监听扫码结果'
        for m in sub.listen():
            try:
                cb_result = json.loads(m['data'])
                if(cb_result['err_code'] == 0):
                    stu_id = biding_info.find_stuid(cb_result['openid'])['stu_id']
                    session['stu_id'] = stu_id
                    if(not stu_id):
                        result_message = {
                        "err_code":-2,
                        "description":"permission denied!"
                        }
                        return json.dumps(result_message)
                    #注意转型,因为sql语句写的是+
                    session['name'] = stu_info.find_name(str(stu_id))
                    result_message = {
                        "err_code":0,
                        "description":"Scan successful!"
                    }
                    return str(json.dumps(result_message))
                else:
                    return str(m['data'])
            except:
                pass

    @app.route('/note/login/callback')
    def wx_callback():
        code = request.args.get("code")
        #这里的state和上面的state是相对应的
        state = request.args.get("state")

        openid_dic = get_openid_oauth2.get_openid(code)

        if(openid_dic["err"] == 0):
            openid = openid_dic["openid"]
            message = {
                "err_code":0,
                "openid":openid
            }
            redis_queue.pub(state,json.dumps(message))
            return render_template('pub-notification/login-success-wx.html')
        else:
            return 'failed'



# sub = redis_queue.sub("123")
# for m in sub.listen():
#     print m['data']
#
#
# redis_queue.pub("123","ddd")